<template>
  <div class="login-in">
    <h1 class="login-head">注 册</h1>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="头像" prop="haedImg">
        <div class="cropper-out">
          <picture-upload></picture-upload>
        </div>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="ruleForm.nickname" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model.number="ruleForm.age" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio label="男" />
          <el-radio label="女" />
          <el-radio label="保密" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input v-model="ruleForm.userEmail" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="again">
        <el-input v-model="ruleForm.again" show-password />
      </el-form-item>
      <el-form-item label="验证码" prop="verify">
        <div class="send-verify">
          <el-input v-model="ruleForm.verify" />
          <el-button
            type="primary"
            style="margin-left: 10px"
            :loading="isLoading"
            @click="sendButHendal(ruleFormRef)"
            >{{ loadingMeg }}</el-button
          >
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" style="margin: 10px 65px"> 注 册 </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import pictureUpload from '@/components/picture-handle/picture-upload.vue'
import { getVCode } from '@/service/email/email'
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
interface RuleForm {
  nickname: string
  age: string
  sex: string
  userEmail: string
  password: string
  again: string
  verify: string
  userBust: string
}
const emit = defineEmits(['doLogin'])
const formSize = ref('default')
let myVerify = ref('')
//设置一分钟只能发送一次验证码
const isLoading = ref(false)
const loadingMeg = ref('发送验证码')
let t1: NodeJS.Timer
let time: number = 60
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  nickname: '',
  age: '',
  sex: '',
  userEmail: '',
  password: '',
  again: '',
  verify: '',
  userBust: ''
})

//确认密码的检验
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else {
    if (value !== ruleForm.password) {
      callback(new Error('两次密码不相同'))
    } else {
      callback()
    }
  }
}
//验证码的校验
const validateVerify = (rule: any, value: any, callback: any) => {
  if (myVerify.value == '') {
    callback(new Error('请输入验证码！'))
  } else if (value != myVerify.value) {
    callback(new Error('验证码错误！'))
  }
  callback()
}
//校验
const rules = reactive<FormRules<RuleForm>>({
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { max: 18, message: '长度不能大于18', trigger: 'blur' }
  ],
  age: [{ type: 'number', message: '年龄必须是数字' }],
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
      message: '请正确输入邮箱',
      trigger: 'change'
    },
    {
      pattern: /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
      message: '请正确输入邮箱',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码信息', trigger: 'blur' },
    {
      pattern: /^(?![a-zA-Z]+$)(?!\d+$)(?![^\da-zA-Z\s]+$).{9,}$/,
      message: '密码至少由9位以上字母、数字、特殊字符组成',
      trigger: 'change'
    },
    {
      pattern: /^(?![a-zA-Z]+$)(?!\d+$)(?![^\da-zA-Z\s]+$).{9,}$/,
      message: '密码至少由9位以上字母、数字、特殊字符组成',
      trigger: 'blur'
    }
  ],
  again: [{ required: true, validator: validatePass2, trigger: 'change' }],
  verify: [
    {
      required: true,
      validator: validateVerify,
      trigger: 'blur'
    }
  ]
})
//提交注册的点击事件
const submitForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valib: any) => {
    //表单校验成功
    if (valib) {
      //校验成功之后，发给父组件
      emit('doLogin', ruleForm)
    } else {
      ElMessage.error('注册失败，请正确填写注册信息！')
    }
  })
}
//发送验证码的点击事件
const sendButHendal = (ruleFormRef: any) => {
  //发送验证码之前对邮箱进行校验
  ruleFormRef.validateField('userEmail', (errorMessage: any) => {
    if (errorMessage == true) {
      sendVCode()
    }
  })
  if (isLoading.value == false) {
    isLoading.value = true
    loadingMeg.value = time + '后再试'
    t1 = setInterval(() => {
      time--
      loadingMeg.value = time + '后再试'
      if (time == 0) {
        loadingMeg.value = '发送验证码'
        isLoading.value = false
        time = 60
        clearInterval(t1)
      }
    }, 1000)
  }
}
//发送验证码
const sendVCode = () => {
  getVCode({ userEmail: ruleForm.userEmail })
    .then((e: any) => {
      console.log('收到验证码为：', e.data)
      myVerify.value = e.data
    })
    .catch(() => {
      ElMessage.error('发送验证码失败！')
    })
}
</script>

<style lang="less" scoped>
.login-in {
  width: 380px;
  border: 1px solid #fff;
  border-radius: 9px;
  background-color: #fff;
  box-shadow: 0 0 90px rgba(255, 255, 255, 0.5) inset;
  padding: 40px 60px 20px 0;
  .login-head {
    font-size: 30px;
    text-align: center;
    margin-bottom: 30px;
    padding-left: 60px;
  }
  .cropper-out {
    margin-left: 40px;
  }
  .send-verify {
    display: flex;
  }
}
</style>
